<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>管理员界面</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://npmcdn.com/flatpickr/dist/l10n/zh.js"></script>
    <style>
        body {
            background-image: url('/picture/info.jpg');
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            background-attachment: fixed;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 1000px;
            margin: 50px auto;
            padding: 20px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 5px;
        }
        .nav-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .nav-tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            margin-bottom: -1px;
        }
        .nav-tab.active {
            border: 1px solid #ddd;
            border-bottom-color: white;
            background-color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group input {
            padding: 8px;
            margin-right: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: center;
        }
        th {
            background-color: #f5f5f5;
        }
        .user-info {
            position: absolute;
            top: 20px;
            right: 20px;
            cursor: pointer;
        }
        .flatpickr-input {
            width: 150px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .flatpickr-calendar {
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            margin: 10px 0;
        }
        
        .progress {
            height: 100%;
            background-color: #4CAF50;
            border-radius: 10px;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="user-info" onclick="showUserInfo()">
        👤 个人信息
    </div>
    
    <div class="container">
        <h1>管理员控制面板</h1>
        <div class="nav-tabs">
            <div class="nav-tab active" onclick="switchTab('classScores')">班级成绩</div>
            <div class="nav-tab" onclick="switchTab('scoreInput')">成绩录入</div>
        </div>
        
        <div id="classScores" class="tab-content active">
            <div class="form-group">
                <input type="text" id="searchMajor" placeholder="专业">
                <input type="text" id="searchClass" placeholder="班级">
                <select id="yearSelect" onchange="loadMonths()">
                    <option value="">选择年份</option>
                </select>
                <select id="monthSelect">
                    <option value="">选择月份</option>
                </select>
                <button onclick="searchClassScores()">查询</button>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <div style="width: 60%;">
                    <table id="scoreTable">
                        <thead>
                            <tr>
                                <th>排名</th>
                                <th>学生姓名</th>
                                <th>语文成绩</th>
                                <th>数学成绩</th>
                                <th>英语成绩</th>
                                <th>总分</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div id="averageScores"></div>
                </div>
                <div style="width: 35%;">
                    <canvas id="averageChart"></canvas>
                </div>
            </div>
        </div>
        
        <div id="scoreInput" class="tab-content">
            <h2>成绩录入</h2>
            <div class="form-group">
                <input type="text" id="studentId" placeholder="学生ID">
                <input type="text" id="studentName" placeholder="学生姓名">
                <input type="number" id="chineseScore" placeholder="语文成绩">
                <input type="number" id="mathScore" placeholder="数学成绩">
                <input type="number" id="englishScore" placeholder="英语成绩">
                <input type="text" id="examDate" placeholder="年/月/日">
                <button onclick="submitScore()">提交</button>
            </div>
            
            <div class="form-group">
                <h3>批量导入成绩</h3>
                <input type="file" id="excelFile" accept=".xlsx,.xls" />
                <button onclick="uploadExcel()">导入 Excel</button>
                <a href="/api/admin/download-template" class="btn">下载模板</a>
                <div id="importProgress" style="display: none;">
                    <div class="progress-bar">
                        <div class="progress" style="width: 0%"></div>
                    </div>
                    <div class="progress-text">准备导入...</div>
                </div>
                <div id="importResult" style="display: none;">
                    <h4>导入结果</h4>
                    <p>总记录数：<span id="totalCount">0</span></p>
                    <p>成功导入：<span id="successCount">0</span></p>
                    <div id="errorList" style="color: red;"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let chart = null;
        let averageChart = null;

        // 页面加载时检查权限
        window.onload = function() {
            console.log('Checking admin privileges...');
            const isAdmin = parseInt(sessionStorage.getItem('isAdmin'));
            console.log('Stored isAdmin:', isAdmin);
            
            if (isAdmin !== 1) {
                console.log('Access denied - redirecting to login');
                alert('无权访问管理员页面！');
                window.location.replace('login.html');
                return;
            }
            
            console.log('Access granted - loading admin page');
            loadYears();
        };

        // 切换标签页
        function switchTab(tabId) {
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            document.querySelector(`.nav-tab[onclick="switchTab('${tabId}')"]`).classList.add('active');
            document.getElementById(tabId).classList.add('active');
            
            if (tabId === 'classAnalysis') {
                loadClassAnalysis();
            }
        }

        // 查询班级成绩
        function searchClassScores() {
            const major = document.getElementById('searchMajor').value;
            const className = document.getElementById('searchClass').value;
            const year = document.getElementById('yearSelect').value;
            const month = document.getElementById('monthSelect').value;
            
            if (!major || !className) {
                alert('请输入专业和班级！');
                return;
            }
            
            if (!year || !month) {
                alert('请选择年份和月份！');
                return;
            }
            
            fetch(`/api/admin/class-scores-by-date?major=${major}&className=${className}&year=${year}&month=${month}`)
                .then(response => response.json())
                .then(data => {
                    updateClassScoreTable(data.scores);
                    updateAverageScores(data.averages);
                    updateAverageChart(data.averages);
                })
                .catch(error => {
                    console.error('获取班级成绩失败：', error);
                    alert('获取班级成绩失败');
                });
        }

        // 更新班级成绩表格
        function updateClassScoreTable(scores) {
            const tbody = document.querySelector('#scoreTable tbody');
            tbody.innerHTML = '';
            
            scores.forEach((score, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${score.studentName}</td>
                    <td>${score.chineseScore}</td>
                    <td>${score.mathScore}</td>
                    <td>${score.englishScore}</td>
                    <td>${score.totalScore}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 更新平均分显示
        function updateAverageScores(averages) {
            document.getElementById('averageScores').innerHTML = `
                <h3>班级平均分</h3>
                <p>语文：${averages.chineseAvg}</p>
                <p>数学：${averages.mathAvg}</p>
                <p>英语：${averages.englishAvg}</p>
                <p>总分：${averages.totalAvg}</p>
            `;
        }

        // 添加更新平均分图表的函数
        function updateAverageChart(averages) {
            const ctx = document.getElementById('averageChart').getContext('2d');
            
            if (averageChart) {
                averageChart.destroy();
            }
            
            averageChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['语文', '数学', '英语', '总分'],
                    datasets: [{
                        label: '班级平均分',
                        data: [
                            averages.chineseAvg,
                            averages.mathAvg,
                            averages.englishAvg,
                            averages.totalAvg
                        ],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(75, 192, 192, 0.5)',
                            'rgba(153, 102, 255, 0.5)'
                        ],
                        borderColor: [
                            'rgb(255, 99, 132)',
                            'rgb(54, 162, 235)',
                            'rgb(75, 192, 192)',
                            'rgb(153, 102, 255)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '班级各科平均分统计'
                        }
                    }
                }
            });
        }

        // 提交成绩
        function submitScore() {
            const studentId = document.getElementById('studentId').value;
            const studentName = document.getElementById('studentName').value;
            const chineseScore = document.getElementById('chineseScore').value;
            const mathScore = document.getElementById('mathScore').value;
            const englishScore = document.getElementById('englishScore').value;
            const examDate = document.getElementById('examDate').value;
            
            if (!studentId || !chineseScore || !mathScore || !englishScore || !examDate) {
                alert('请填写所有必要字段！');
                return;
            }
            
            fetch('/api/admin/submit-score', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                body: JSON.stringify({
                    studentId: studentId,
                    chineseScore: parseFloat(chineseScore),
                    mathScore: parseFloat(mathScore),
                    englishScore: parseFloat(englishScore),
                    examDate: examDate
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('成绩录入成功！');
                    clearScoreForm();
                } else {
                    alert(data.message || '学生不存在或输入信息错误');
                }
            })
            .catch(error => {
                console.error('成绩录入失败：', error);
                alert('学生不存在或输入信息错误');
            });
        }

        // 清空成绩录入表单
        function clearScoreForm() {
            document.getElementById('studentId').value = '';
            document.getElementById('studentName').value = '';
            document.getElementById('chineseScore').value = '';
            document.getElementById('mathScore').value = '';
            document.getElementById('englishScore').value = '';
            document.getElementById('examDate').value = '';
        }

        // 显示用户信息
        function showUserInfo() {
            const userId = sessionStorage.getItem('userId');
            const username = sessionStorage.getItem('username');
            const major = sessionStorage.getItem('major');
            const className = sessionStorage.getItem('className');
            
            alert(`
                管理员信息：
                ID: ${userId}
                用户名: ${username}
                专业: ${major}
                班级: ${className}
                身份: 管理员
            `);
        }

        // 加载年份选项
        function loadYears() {
            fetch('/api/admin/exam-years')
                .then(response => response.json())
                .then(years => {
                    const yearSelect = document.getElementById('yearSelect');
                    yearSelect.innerHTML = '<option value="">选择年份</option>';
                    years.forEach(year => {
                        yearSelect.innerHTML += `<option value="${year}">${year}年</option>`;
                    });
                })
                .catch(error => console.error('获取年份失败：', error));
        }

        // 加载月份选项
        function loadMonths() {
            const year = document.getElementById('yearSelect').value;
            if (!year) {
                document.getElementById('monthSelect').innerHTML = '<option value="">选择月份</option>';
                return;
            }

            fetch(`/api/admin/exam-months/${year}`)
                .then(response => response.json())
                .then(months => {
                    const monthSelect = document.getElementById('monthSelect');
                    monthSelect.innerHTML = '<option value="">选择月份</option>';
                    months.forEach(month => {
                        monthSelect.innerHTML += `<option value="${month}">${month}月</option>`;
                    });
                })
                .catch(error => console.error('获取月份失败：', error));
        }

        // 初始化日期选择器
        flatpickr("#examDate", {
            dateFormat: "Y/m/d",
            locale: "zh",
            placeholder: "年/月/日",
            enableTime: false,
            altInput: true,
            altFormat: "Y年m月d日",
            dateFormat: "Y-m-d",
            minDate: "2000-01-01",
            maxDate: "2099-12-31",
            disableMobile: "true"
        });

        // 添加上传 Excel 的函数
        function uploadExcel() {
            const fileInput = document.getElementById('excelFile');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请选择文件！');
                return;
            }
            
            // 显示进度条
            const progressDiv = document.getElementById('importProgress');
            const progressBar = progressDiv.querySelector('.progress');
            const progressText = progressDiv.querySelector('.progress-text');
            const resultDiv = document.getElementById('importResult');
            
            progressDiv.style.display = 'block';
            resultDiv.style.display = 'none';
            progressBar.style.width = '0%';
            progressText.textContent = '准备导入...';
            
            const formData = new FormData();
            formData.append('file', file);
            
            fetch('/api/admin/import-scores', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新进度条为100%
                    progressBar.style.width = '100%';
                    progressText.textContent = '导入完成';
                    
                    // 显示结果
                    document.getElementById('totalCount').textContent = data.total;
                    document.getElementById('successCount').textContent = data.successCount;
                    
                    // 显示错误信息
                    const errorList = document.getElementById('errorList');
                    errorList.innerHTML = '';
                    if (data.errors && data.errors.length > 0) {
                        data.errors.forEach(error => {
                            errorList.innerHTML += `<p>${error}</p>`;
                        });
                    }
                    
                    resultDiv.style.display = 'block';
                    fileInput.value = '';
                } else {
                    alert('导入失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('导入失败：', error);
                alert('导入失败：' + error.message);
            });
        }
    </script>
</body>
</html> 